package com.joinlabs.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import com.joinlabs.entity.Address;
import com.joinlabs.entity.Order;
import com.joinlabs.entity.Orderitem;
import com.joinlabs.entity.ShopcarItem;
import com.joinlabs.entity.ShopcarItemPro;
import com.joinlabs.entity.User;
import com.joinlabs.mapper.AddressMapper;
import com.joinlabs.mapper.OrderMapper;
import com.joinlabs.mapper.OrderitemMapper;
import com.joinlabs.mapper.ShopcarMapper;
import com.joinlabs.mapper.WaresMapper;
import com.joinlabs.service.IOrderService;
import com.joinlabs.service.IShopcarService;
@Service
public class OrderServiceImpl implements IOrderService {
	
	@Resource(name="orderMapper")
	private OrderMapper omap;
	
	@Resource(name="orderitemMapper")
	private OrderitemMapper oimap;
	
	@Resource(name="waresMapper")
	private WaresMapper wmap;
	
	@Resource(name="shopcarServiceImpl")
	private IShopcarService scService;
	
	@Resource(name="addressMapper")
	private AddressMapper addmap;
	//查询用户的所有购物车并将购物车子项封装进购物车类中返回给控制层
	@Override
	public List<Order> selcetByUser(String userId) {
		List<Order> orders = omap.selectByUser(userId);
		

		for(Order order: orders) {
			List<Orderitem> items =  oimap.selectItemById(order.getOrderId());
			for(Orderitem item:items) {
				
				//根据订单子项的waresId获取商品的商品名并存入orderItem中
				String wareName = wmap.selectByPrimaryKey(item.getWaresId()).getWaresName();
				
				item.setWaresName(wareName);
				
			}
			order.setItems(items);
			
		}
		
		return orders;
	}
	
	/*
	 * 查找用户的收货地址
	 */
	
	public List<Address> selectAllAddress(User user){
		//System.out.println(user.getUserId().getClass().toString());
		//System.out.println(user.getUserId());
		List<Address> addrs =  addmap.selectByUser(user.getUserId());
		//if(addrs.size() == 0)return null;
		
		//System.out.println(addrs);
		return addrs;
	}
	
	/*
	 * 	付款时将收货地址存入数据库
	 *
	 */
	public void pay(String oid,long addr) {
		
		
			Order order = omap.selectByPrimaryKey(oid);
			order.setZyAid(addr);
			
			omap.updateByPrimaryKey(order);
		
	}
	
	
	/*
	 * 付款成功后修改订单状态
	 */
	public int payOver(String oid) {
		
			Order over = omap.selectByPrimaryKey(oid);
			
			//System.out.println(oid);
			over.setOrderState((long)1);//修改为已付款
			
			int row = omap.updateByPrimaryKey(over);
			return  row;
	}
	
	@Autowired
	DataSourceTransactionManager dataSourceTransactionManager;
	@Autowired
	TransactionDefinition transactionDefinition;
	//将选中的购物车子项添加到订单
	public Order commitOrder(BigDecimal[] carId,User user) {
		//打开事务
		TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
		Order order = new Order();
		
		//scService.delWaresCountById(item);
		try {
			List<Orderitem> items = new ArrayList<Orderitem>();
			
			//System.out.println(cids.length);
			//System.out.println(user.getUserId());
			
			//生成订单对象
			order.setUser(user); 
			order.setOrderState((long)0);//未付款
			order.setUserId(user.getUserId());
			order.setOrderTime(getTime());
			order.setOrderId(getOid(user));
			
			//System.out.println(Arrays.toString(cids));
			
			//查询将生成订单的购物车子项
			List<ShopcarItem> item = scService.findShopcarItemsByIds(carId);
			
			//System.out.println(item);
			int index = 0;//用于获取购物车子项集合的指定目标
			for (BigDecimal i : carId) {
				
				Orderitem oitem = new Orderitem();
				
				//把购物车子项包装成订单子项
				oitem.setOrderItemid(item.get(index).getCarId());
				oitem.setWaresId(item.get(index).getWaresId());
				oitem.setWaresColor(item.get(index).getWaresColor());
				oitem.setWaresEdition(item.get(index).getWaresEdition());
				oitem.setWaresCount(item.get(index).getWaresCount());
				oitem.setOrderId(order.getOrderId());
				long count =item.get(index).getWaresCount().longValue();//用于计算订单子项的总价
				oitem.setOrderPrice(count * item.get(index).getWaresPrice());
				oitem.setImgpath(item.get(index).getWaresImg());
				
				//oitem.setWares(wmap.selectByPrimaryKey(oitem.getWaresId()));
				
				//取得货物名
				oitem.setWaresName(wmap.selectByPrimaryKey(oitem.getWaresId()).getWaresName());
				
				
				//向订单表插入订单子项
				oimap.insert(oitem);
				//System.out.println(oitem);
				items.add(oitem);
				//System.out.println("success");
				index++;
			}
			//System.out.println(items);
			order.setItems(items);
			//System.out.println("order set success");
			
			//将订单添加进数据库
			omap.insert(order);
			//System.out.println("订单已添加");
			
			//减少库存增加销量
			scService.delWaresCountById(item);
			
			System.out.println("库存修改完毕");
			
			//删除生成订单的购物车子项
			scService.delShopcarItemsByIds(carId);
			// 提交事务
			dataSourceTransactionManager.commit(transactionStatus);
			return order;
		} catch (Exception e) {
			// TODO: handle exception
			
			//回滚
			dataSourceTransactionManager.rollback(transactionStatus);
			
		}
		return null;
		
	}
	
	//生成订单时间
	public String getTime() {
		Date date = new Date();
		
		String time = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(time);
		
		return sdf.format(date);
	}
	
	
	//生成订单号
	public String getOid(User user) {
		Date date = new Date();
		long time = date.getTime();
		
		//将时间戳和用户哈希码拼接成订单号
		String oid = time + user.hashCode() +"";
		
		return oid;
	}

	
	//收货	
	@Override
	public void takeOver(String oid) {
		Order order = omap.selectByPrimaryKey(oid);
		
		//把订单状态改为已收货
		order.setOrderState((long)3);
		omap.updateByPrimaryKey(order);
		
	}
	
	
	//用主键来搜索订单
	@Override
	public Order selectOrderByPK(String orderId) {
		Order order = omap.selectByPrimaryKey(orderId);
		List<Orderitem> items = oimap.selectItemById(orderId);
		for(Orderitem item:items) {
			
			//把货物名传入Orderitem对象以显示在订单页
			String wareName = wmap.selectByPrimaryKey(item.getWaresId()).getWaresName();
			
			item.setWaresName(wareName);
		}
		order.setItems(items);
		return order;
		
	}
	//删除订单项
	@Override
	public void delete(String orderId) {
		// TODO Auto-generated method stub
		omap.deleteByPrimaryKey(orderId);
		List<Orderitem> items = oimap.selectItemById(orderId);
		
		for(Orderitem item:items)
		oimap.deleteByPrimaryKey(item.getOrderItemid());
	}
	//更新订单数据
	@Override
	public void updata(Order order) {
		
		System.out.println(order);
		omap.updateByPrimaryKey(order);
		
	}

	@Override
	public int selectOrdercount() {

		int row = omap.selectOrdercount();
		
		return row;
	}
}
